package com.facemox.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.facemox.bean.EnvConfig;
import com.facemox.bean.GlobalParameter;
import com.facemox.service.EnvConfigService;
import com.facemox.service.GlobalParameterService;

@RestController
public class EnvConfigController {
    
    @Autowired
    private EnvConfig envConfig;
    
    @Autowired
    private EnvConfigService envConfigService;
    
    Map<String,Object> map = new HashMap<String, Object>();
    
    @RequestMapping("add_env_config")
    public int addEnvConfig(HttpServletRequest request) {
        map.clear();
        Enumeration<String> gps = request.getParameterNames();
        while(gps.hasMoreElements()) {
            String envConfig = gps.nextElement();
            String[] parameterValues = request.getParameterValues(envConfig);
            map.put(parameterValues[0].trim(), parameterValues[1].trim());
        }
        
        // Map转JSON
        String envConfigStr = JSONArray.toJSONString(map);
        
        envConfig.setParamBody(envConfigStr);
        
        EnvConfig config = envConfigService.getEnvConfig();
        
        if(config==null) {
            int effectLine = envConfigService.addEnvConfig(envConfig);
            return effectLine;
        }else {
            int effectLine = envConfigService.UpdateGlobalParameter(envConfig);
            return effectLine;
        }
    }
    
    @RequestMapping("get_env_config")
    public Object getEnvConfig() {
        EnvConfig envConfig = envConfigService.getEnvConfig();
        JSONObject envConfigMap = null;
        if(envConfig!=null) {
            
            String paramBody = envConfig.getParamBody();
            // JSON转Map
            envConfigMap = JSON.parseObject(paramBody);
            
        }else {
            return "";
        }
        return envConfigMap;
    }
}
